<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="uploadExcel">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="addEmployeesFn">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="{row}">
              <image-holder class="staffPhoto" :src="row.staffPhoto" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" sortable :sort-method="workNumberSortFn" />
          <el-table-column label="聘用形式" prop="">
            <template v-slot="scope">
              <span>{{ formatter(scope.row) }}</span>
            </template>
          </el-table-column>formOfEmployment
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" :formatter="time" />
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="lookDetailFn(row.id,row.formOfEmployment)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoleFn(row)">分配角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹框组件 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @closed="closeDialogFn">
        <employ-form
          ref="employForm"
          :show.sync="showDialog"
          :tree-data="treeData"
          @addEmloyee="addEmloyeeslistFn"
        />
      </el-dialog>

      <!-- 员工-分配角色权限 - 弹窗 -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog">
        <!-- 设置角色组件 -->
        <assign-role-dialog ref="RoleDialog" :show.sync="showRoleDialog" :all-roles-list="allRolesList" @roleEV="roleListFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeesListAPI, getdepartmentsAPI, addEmployeesListAPI, getRoleAPI, userPhotoAPI, saveEmployeesRoleAPI } from '@/api'
import context from '@/api/context/index'
import dayjs from 'dayjs'
import EmployForm from './components/employForm.vue'
import assignRoleDialog from './components/assignRoleDialog.vue'
import { transTree } from '@/utils/index.js'

export default {
  name: 'Employees',
  components: {
    EmployForm, assignRoleDialog
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      // hireTypeList: employees.hireType
      showDialog: false,
      // 树形部门数组
      treeData: [],
      // 获取所有员工列表
      allEmployeesList: [],
      // 控制弹窗隐藏显示
      showRoleDialog: false,
      // 获取所有角色列表
      allRolesList: [],
      // 获取员工id
      rolesId: ''
    }
  },
  created() {
    // 获取员工列表
    this.getEmployeesListFn()
    // 获取企业部门信息
    this.getdepartmentsAPIFn()
  },
  methods: {

    // 获取员工列表
    async getEmployeesListFn() {
      const res = await getEmployeesListAPI(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
      // 获取所有员工列表
      const { data } = await getEmployeesListAPI({ page: 1, size: res.data.total })
      // console.log(data)
      this.allEmployeesList = data.rows
      // 获取所有的角色列表
      const roleRes = await getRoleAPI({ page: 1, size: res.data.total })
      // console.log(roleRes)
      this.allRolesList = roleRes.data.rows
    },

    // 获取企业部门信息
    async getdepartmentsAPIFn() {
      const res = await getdepartmentsAPI()
      // console.log(res)
      this.treeData = transTree(res.data.depts, '')
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeesListFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesListFn()
    },

    // 聘用形式数据处理
    formatter(row) {
      const obj = context.hireType.find(item => item.id === parseInt(row.formOfEmployment))
      return obj ? obj.value : '未知'
    },

    // 工号排序方法
    workNumberSortFn(a, b) {
      // console.log(a, b)
      return parseInt(a.workNumber) - parseInt(b.workNumber)
    },

    // 格式化时间
    time(row) {
      // console.log(row)
      return dayjs(row.timeOfEntry).format('YYYY-MM-DD')
    },

    // 新增员工
    addEmployeesFn() {
      this.showDialog = true
    },
    //  新增员工方法
    async addEmloyeeslistFn(formData) {
      const res = await addEmployeesListAPI(formData)
      // console.log(res)
      if (res.code === 10000) this.$message.success(res.message)
      this.getEmployeesListFn()
    },

    // 关闭弹窗清空表单
    closeDialogFn() {
      this.$refs.employForm.$refs.addForm.resetFields()
    },

    // 导入Excel
    uploadExcel() {
      this.$router.push('/excel')
    },

    // 导出Excel
    exportExcel() {
      import('@/vendor/Export2Excel').then(excel => {
        // 准备数据
        const tHeader = ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间']
        const zhAndEnObj = {
          '姓名': 'username',
          '头像': 'staffPhoto',
          '手机号': 'mobile',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName',
          '入职时间': 'timeOfEntry'

        }
        const data = this.allEmployeesList.map((enObj, index) => {
          const newArr = []
          tHeader.forEach(zhKey => {
            if (zhKey === '序号') {
              newArr.push(index + 1)
            } else {
              const enKey = zhAndEnObj[zhKey]
              const value = enObj[enKey]
              if (enKey === 'formOfEmployment') {
                const obj = context.hireType.find(item => item.id === parseInt(value))
                newArr.push(obj ? obj.value : '未知')
              } else {
                newArr.push(value)
              }
            }
          })
          return newArr
        })

        // const data = this.employeesList.map(obj => {
        //   return Object.values(obj)
        // })

        // 生成excel
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '文件名',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },

    // 查看员工详情
    lookDetailFn(employeeId, formOfEmploymentId) {
      this.$router.push(`/employees/detail?id=${employeeId}&form=${formOfEmploymentId}`)
    },

    // 分配角色
    async assignRoleFn(rowObj) {
      const res = await userPhotoAPI(rowObj.id)
      // console.log(res)
      this.rolesId = rowObj.id
      this.showRoleDialog = true
      this.$nextTick(() => {
        // console.log(111)
        this.$refs.RoleDialog.roleListId = res.data.roleIds
      })
    },

    // 保存员工的分配的角色信息
    async roleListFn(roleObj) {
      const res = await saveEmployeesRoleAPI({ id: this.rolesId, roleIds: roleObj })
      console.log(res)
    }

  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
